﻿using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using VM.Common.Result;
using VM.Entity.EntityMap.Condition;
using VM.Entity.EntityMap.Menu;
using VM.Entity.EntityMap.Token;
using VM.IDAL;

namespace VM.DAL
{
    public abstract class BaseDAL : IBaseDAL
    {

        /// <summary>
        /// 
        /// </summary>
        protected ISqlSugarClient _Client { get; set; }

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="context"></param>
        public BaseDAL(ISqlSugarClient client)
        { 

            _Client = client;
            // 在执行前注册 OnLogExecuting 事件
            _Client.Aop.OnLogExecuting = (sql, pars) =>
            {
                string s = sql;
                Console.WriteLine(s);

            };// 在执行前注册 OnLogExecuting 事件


        }

        #region Query

        /// <summary>
        /// 主键查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public T Find<T>(int id) where T : class
        {
            return _Client.Queryable<T>().InSingle(id);
        }

        /// <summary>
        /// 主键查询-异步版本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> FindAsync<T>(int id) where T : class
        {
            return await _Client.Queryable<T>().InSingleAsync(id);
        }

        /// <summary>
        /// 不应该暴露给上端使用者，尽量少用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        [Obsolete("尽量避免使用，using 带表达式目录树的代替")]
        public ISugarQueryable<T> Set<T>() where T : class
        {
            return _Client.Queryable<T>();
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcWhere"></param>
        /// <returns></returns>
        public ISugarQueryable<T> Query<T>(Expression<Func<T, bool>> funcWhere) where T : class
        {
            
           
            return _Client.Queryable<T>().Where(funcWhere);
        }



        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcWhere"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="funcOrderby"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public PagingData<T> QueryPage<T>( Expression<Func<T, bool>> funcWhere, int pageSize, int pageIndex, Expression<Func<T, object>> funcOrderby, bool isAsc = true) where T : class
        {
            var list = _Client.Queryable<T>();
        
            if (funcWhere != null)
            {
                list = list.Where(funcWhere);
            }
            if (funcOrderby != null)
            { 
                list = list.OrderByIF(true, funcOrderby, isAsc ? OrderByType.Asc : OrderByType.Desc);
             }
            PagingData<T> result = new PagingData<T>()
            {
                dataList = list.ToPageList(pageIndex, pageSize),
                pageIndex = pageIndex,
                pageSize = pageSize,
                recordCount = list.Count(),
            };
            return result;
        }


        /// <summary>
        /// 动态过滤条件的查询 funcWhere
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="funcWhere"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="funcOrderby"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public PagingData<T> QueryPageConditon<T>(List<Condition> funcWhere, int pageSize, int pageIndex, Expression<Func<T, object>> funcOrderby, bool isAsc = true) where T : class
        {

            string funcWherCondition = JsonConvert.SerializeObject(funcWhere);
             
            //5.0.5.1 Json直接序列化
            var whereList = _Client.Utilities.JsonToConditionalModels(funcWherCondition);
            var list = _Client.Queryable<T>();
   

            if (funcWhere != null && funcWhere.Count !=0)
            {
                list = list.Where(whereList);
            }
            if (funcOrderby != null)
            {
                list = list.OrderByIF(true, funcOrderby, isAsc ? OrderByType.Asc : OrderByType.Desc);
            }
            PagingData<T> result = new PagingData<T>()
            {
                dataList = list.ToPageList(pageIndex, pageSize),
                pageIndex = pageIndex,
                pageSize = pageSize,
                recordCount = list.Count(),
                searchString = funcWherCondition
            };
         
            return result;
        }
         
        public PagingData<sys_menu> QueryPageList<T>(  int pageSize, int pageIndex) where T : class
        {

            var list = _Client.Queryable<sys_menu>()
                         .LeftJoin<sys_menuMeta>((u, o) => u.id == o.parentId)
                         .Select((u,o) => new sys_menu
                         { 
                             meta = o 
                         }, true)
                         ;

            PagingData<sys_menu> result = new PagingData<sys_menu>()
            {
                dataList = list.ToPageList(pageIndex, pageSize),
                pageIndex = pageIndex,
                pageSize = pageSize,
                recordCount = list.Count(),
            };
            return result;
         
        }



        #endregion

        #region Insert

        /// <summary>
        /// 新增数据-同步版本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public T Insert<T>(T t) where T : class, new()
        {
            return _Client.Insertable(t).ExecuteReturnEntity();
        }

        /// <summary>
        /// 新增数据-异步版本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<T> InsertAsync<T>(T t) where T : class, new()
        { 
            return await _Client.Insertable(t).ExecuteReturnEntityAsync();
        }

        /// <summary>
        /// 批量新增-事务执行
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tList"></param>
        /// <returns></returns>
        public async Task<bool> InsertList<T>(List<T> tList) where T : class, new()
        {
            return await _Client.Insertable(tList.ToList()).ExecuteCommandIdentityIntoEntityAsync();
        }



        //public async Task<bool> InsertObj<T>(T t) where T : class, new()
        //{
        //    return await _Client.InsertNav(t)
        //    .Include(z1 => z1.Books)
        //    .ExecuteCommand();

        //}

        /// <summary>
        /// 级联对象的插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="mainObject"></param>
        /// <param name="childObjects"></param>
        /// <param name="foreignKeyExpression"></param>
        public void InsertObj<T, TKey>(T mainObject, List<T> childObjects, Expression<Func<T, TKey>> foreignKeyExpression) where T : class, new()
        {
          
            // 插入主表对象
            var mainId = _Client.Insertable(mainObject).ExecuteReturnIdentity();

            // 遍历子表对象列表，设置外键属性
            foreach (var childObject in childObjects)
            {
                var foreignKeyProperty = (MemberExpression)foreignKeyExpression.Body;
                var foreignKey = (PropertyInfo)foreignKeyProperty.Member;
                foreignKey.SetValue(childObject, mainId);

                _Client.Insertable(childObject).ExecuteCommand();
            }
        }

        #endregion

        #region Update
        /// <summary>
        /// 是没有实现查询，直接更新的,需要Attach和State
        /// 
        /// 如果是已经在context，只能再封装一个(在具体的service)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        public async Task<bool> UpdateAsync<T>(T t) where T : class, new()
        {
            if (t == null) throw new Exception("t is null");

            return await _Client.Updateable(t).IgnoreColumns(ignoreAllNullColumns: true, ignoreAllDefaultValue: true).ExecuteCommandHasChangeAsync();
               
        }

        public void Update<T>(List<T> tList) where T : class, new()
        {
            
            _Client.Updateable(tList)
                .IgnoreColumns(ignoreAllNullColumns: true, ignoreAllDefaultValue: true)
                .ExecuteCommand();
         
        }

        //public void UpdateByNotPrimaryKey<T>(List<T> tList, Expression<Func<T, bool>> whereExpression, Expression<Func<T, object>> columnsExpression) where T : class, new()
        //{

        //    _Client.Updateable(tList).UpdateColumns(columnsExpression).Where(whereExpression).ExecuteCommand();


        //    _Client.Aop.DataExecuting = (s, p) =>
        //    {
        //        string ss = s.ToString();
        //        string pp=p.ToString();

        //    };
        //}


        //public bool UpdateByNotPrimaryKey<T>(Expression<Func<T, bool>> whereExpression, Expression<Action<T>> columnsExpression) where T : class, new()
        //{
        //    // 更新操作
        //    _Client.Updateable<T>()
        //        .SetColumns(columnsExpression.Compile())
        //        .Where(whereExpression)
        //        .ExecuteCommand();

        //    return true;
        //}


        public int  UpdateByNotPrimaryKey<T>(Expression<Func<T, bool>> whereExpression, Expression< Func<T,T>> columnsExpression) where T : class, new()
        {

            int result = 0;


            // 更新操作
            try
            {
                //_Client.Updateable<T>()
                //    .SetColumns(columnsExpression)
                //    .Where(whereExpression)
                //    .IgnoreColumns(ignoreAllNullColumns: true)
                //    .ExecuteCommand();
                //result = _Client.Updateable<Sys_RefreshToken>()
                //       .SetColumns(it => new Sys_RefreshToken() { RefreshDateTimes = DateTime.Now, EndDateTimes = DateTime.Now.AddDays(3) })//类只能在表达示里面不能提取
                //       .Where(it => it.PublicKey == "1")
                //       .ExecuteCommand();
                result = _Client.Updateable<T>()
                  .SetColumns(columnsExpression)//类只能在表达示里面不能提取
                  .Where(whereExpression)
                  .ExecuteCommand();

            }
            catch (Exception e){ 
            
               Console.WriteLine(e.Message);
            }
            return result;
        }




        #endregion

        #region Delete
        /// <summary>
        /// 先附加 再删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        public void Delete<T>(T t) where T : class, new()
        {
            _Client.Deleteable(t).ExecuteCommand();
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pId"></param>
        /// <returns></returns>
        public bool Delete<T>(object pId) where T : class, new()
        {
            T t = _Client.Queryable<T>().InSingle(pId);
            return _Client.Deleteable(t).ExecuteCommand() > 0;
        }

        public void Delete<T>(List<T> tList) where T : class
        {
            _Client.Deleteable(tList).ExecuteCommand();
        }
        #endregion


        #region Other 
        ISugarQueryable<T> IBaseDAL.ExcuteQuery<T>(string sql) where T : class
        {
            return _Client.SqlQueryable<T>(sql);
        }
        public void Dispose()
        {
            if (_Client != null)
            {
                _Client.Dispose();
            }
        }

        public ISugarQueryable<T> ExcuteQuery<T>(string sql) where T : class, new()
        {
            throw new NotImplementedException();
        }

    
        #endregion



    }
}
